package cn.uniquesoft.controller;

import cn.uniquesoft.controller.base.BaseController;
import cn.uniquesoft.manager.ClientManager;
import cn.uniquesoft.page.DataGrid;
import cn.uniquesoft.service.IArticleService;
import cn.uniquesoft.service.ISearchService;
import cn.uniquesoft.util.ContextUtil;
import cn.uniquesoft.util.DateUtil;
import cn.uniquesoft.util.FileUtil;
import cn.uniquesoft.util.ImageUploadUtil;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.ArticleVO;
import cn.uniquesoft.vo.SearchVO;
import cn.uniquesoft.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Date;

@Controller
@RequestMapping(value = "/article")
public class ArticleController extends BaseController<ArticleVO> {

    private Logger logger = LoggerFactory.getLogger(ArticleController.class);
    @Autowired
    private ISearchService searchService;

    private IArticleService articleService;

    @Value("${zhxz.url}")
    private String zhxzUrl;

    //文件导入格式
    private static String fileExts = ".jpg,.gif,.png,.bmp";

    public ArticleController(IArticleService articleService) {
        super();
        this.articleService = articleService;
        this.baseService = articleService;
        this.indexName = "article/index";
    }

    @RequestMapping(value = "/index1")
    public String index1(Model model) {
        UserVO userVO = null;
        try {
            userVO = ClientManager.getInstance().getClient().getUser();
        } catch (Exception e) {

        }
        model.addAttribute("iusertype", userVO.getIusertype());
        return indexName;
    }
    /**
     * ckeditor图片上传
     *
     * @param request
     * @param response
     * @Title imageUpload
     */
    @RequestMapping("imageUpload")
    public void imageUpload(HttpServletRequest request, HttpServletResponse response) {
        String DirectoryName = "files/pic";
        ImageUploadUtil.ckeditor(request, response, DirectoryName,zhxzUrl);
    }

    /**
     * @author wty
     * @DESCRIPTION: 添加数据
     * @params: 
     * @return: 
     * @Date: 2018/12/21 13:07 
     * @Modified By:  
    */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    @Override
    public AnswerVO save(ArticleVO item) {
//		ModelAndView result = new ModelAndView(this.viewPath+"index");
        AnswerVO answerVO = new AnswerVO();
        UserVO userVO = null;
        try {
            userVO = ClientManager.getInstance().getClient().getUser();
        } catch (Exception e) {

        }
        if (userVO != null) {
            item.setIorgname(userVO.getIorgname());
            item.setIusertype(userVO.getIusertype());
        }
        //获取绝对路径
        String directory = "files/pic";
        String absPath = ContextUtil.getRequest().getSession().getServletContext().getRealPath(directory);
        OutputStream out = null;
        InputStream filecontent = null;
        try {
            Part filePart = ContextUtil.getRequest().getPart("file");
            //源文件名称
            String fileName = getFileName(filePart);
            String ext = fileName.substring(fileName.lastIndexOf("."));
            if (fileExts.indexOf(ext) == -1) {
                answerVO.setSuccess(false);
                answerVO.setMsg("上传失败,只能上传" + fileExts + "格式的文件！");
                return answerVO;
            }
            //存储的名称
            String saveName = "fm" + DateUtil.dateToDateFullString(new Date()) + ext;
            String savePath = absPath + File.separator + saveName;
//			File ffile = new File(savePath);
            /*if (!ffile.exists()) {
				ffile.mkdir();
			}*/
            //输出流
            out = new FileOutputStream(savePath);
            //输入流
            filecontent = filePart.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            //封面图片地址
            item.setCcoverimg(saveName);
            String ccontent = item.getCcontent();
            int count = this.baseService.save(item);


            if (count > 0) {
                answerVO.setSuccess(true);
                answerVO.setMsg("操作成功！");
                //生成html文件用于app调用
                //存储路径
                String htmlPath = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/files/tw");
                fileName = "tw_" + userVO.getIid() + "_" + item.getIid() + ".html";
                FileUtil.parseHtml(htmlPath, item.getCtitle(), fileName, ccontent);
                item.setCurl(fileName);
                this.articleService.updateUrl(item);
                SearchVO searchVO = new SearchVO();
                searchVO.setTname("article");
                searchVO.setTid(item.getIid()+"");
                searchVO.setTvalue(item.toString());
                searchVO.setTtitle(item.getCtitle());
                System.out.println(item.toString());
                searchVO.setId(searchVO.getTid() + "_" + searchVO.getTname());
                this.searchService.save(searchVO);
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("操作失败！");
            }
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("操作失败！");
            return answerVO;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (filecontent != null) {
                try {
                    filecontent.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return answerVO;
    }

    /**
     * @author wty
     * @DESCRIPTION: 修改
     * @params: 
     * @return: 
     * @Date: 2018/12/21 13:07 
     * @Modified By:  
    */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    @Override
    public AnswerVO edit(ArticleVO item) {
        AnswerVO answerVO = new AnswerVO();

        //获取绝对路径
        String directory = "files/pic";
        String absPath = ContextUtil.getRequest().getSession().getServletContext().getRealPath(directory);
        OutputStream out = null;
        InputStream filecontent = null;
        try {
            Part filePart = ContextUtil.getRequest().getPart("file");
            String fileName = getFileName(filePart);
            if(null != fileName && fileName.length() > 0){
                //源文件名称
                String ext = fileName.substring(fileName.lastIndexOf("."));
                if (fileExts.indexOf(ext) == -1) {
                    answerVO.setSuccess(false);
                    answerVO.setMsg("上传失败,只能上传" + fileExts + "格式的文件！");
                    return answerVO;
                }
                //存储的名称
                String saveName = "fm" + DateUtil.dateToDateFullString(new Date()) + ext;
                String savePath = absPath + File.separator + saveName;
                //输出流
                out = new FileOutputStream(savePath);
                //输入流
                filecontent = filePart.getInputStream();

                int read = 0;
                final byte[] bytes = new byte[1024];

                while ((read = filecontent.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                //封面图片地址
                item.setCcoverimg(saveName);
            }
            String ccontent = item.getCcontent();
            //生成html文件用于app调用
            //存储路径
            String htmlPath = ContextUtil.getRequest().getSession().getServletContext().getRealPath("/files/tw");
            fileName = "tw_" + item.getIcreator() + "_" + item.getIid() + ".html";
            FileUtil.parseHtml(htmlPath, item.getCtitle(), fileName, ccontent);
            item.setCurl(fileName);
            int count = this.baseService.edit(item);
            if (count > 0) {
                this.searchService.remove(item.getIid()+"", "article");
                SearchVO searchVO = new SearchVO();
                searchVO.setTname("article");
                searchVO.setTid(item.getIid()+"");
                searchVO.setTvalue(item.toString());
                System.out.println(item.toString());
                searchVO.setTtitle(item.getCtitle());
                searchVO.setId(searchVO.getTid() + "_" + searchVO.getTname());
                this.searchService.save(searchVO);
                answerVO.setSuccess(true);
                answerVO.setMsg("操作成功！");
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("操作失败！");
            }
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("操作失败！");
            return answerVO;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (filecontent != null) {
                try {
                    filecontent.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return answerVO;
    }
    /**
     * @author wty
     * @DESCRIPTION: 获取文件名
     * @params: 
     * @return: 
     * @Date: 2018/12/21 13:08 
     * @Modified By:  
    */
    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        logger.info("Part Header = {0}", partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

    @RequestMapping(value = "/removeById")
    @ResponseBody
    @Override
    public AnswerVO removeById(int  iid) {
        AnswerVO answerVO = new AnswerVO();
        try {
            int result = this.baseService.removeById(iid);

            if (result > 0) {
                this.searchService.remove(iid+"", "article");
                answerVO.setSuccess(true);
                answerVO.setMsg("删除成功!");
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("删除失败!");
            }
            answerVO.setData(result);
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("删除失败," + e.getMessage());
        }

        return answerVO;
    }

    @RequestMapping(value = "/removeByIds")
    @ResponseBody
    @Override
    public AnswerVO removeByIds(String ids) {
        AnswerVO answerVO = new AnswerVO();
        try {
            int result = this.baseService.removeByIds(ids);

            if (result > 0) {
                String[] ss = ids.split(",");
                for(int i=0;i<ss.length;i++){
                    this.searchService.remove(ss[i]+"", "article");
                }
                answerVO.setSuccess(true);
                answerVO.setMsg("删除成功!");
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("删除失败!");
            }
            answerVO.setData(result);
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("删除失败," + e.getMessage());
        }

        return answerVO;
    }

    @RequestMapping(value = "/shenhe")
    @ResponseBody
    public AnswerVO shenhe(ArticleVO item) {
        AnswerVO answerVO = new AnswerVO();
        int result = this.articleService.shnehe(item);
        if (result > 0) {
            answerVO.setSuccess(true);
            answerVO.setMsg("审核成功!");
        } else {
            answerVO.setSuccess(false);
            answerVO.setMsg("审核失败!");
        }
        return answerVO;
    }

    @RequestMapping(value = "/pageQuery")
    @ResponseBody
    public DataGrid pageQuery(ArticleVO item) {
        DataGrid dg = new DataGrid();
        UserVO userVO = null;
        try {
            userVO = ClientManager.getInstance().getClient().getUser();
        } catch (Exception e) {

        }
        if (userVO != null) {
            if (userVO.getIvisible() == 1) {

            } else if (userVO.getIvisible() == 2) {
                item.setIusertype(userVO.getIusertype());
                System.out.println(item.getIusertype() + "xxxxxxxxxxxxxxx");
                item.setIorgname(userVO.getIorgname());
            } else {
                item.setIcreator(userVO.getIid());
            }
        }
        System.out.println(item.getIusertype() + "yyyyyyyyyyyyyyyyyy");
        return this.baseService.pageQuery(item);
    }
}
